package com.huatai.bpmn.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huatai.bpmn.entity.TbCommitEntity;
import com.huatai.bpmn.mapper.TbCommitMapper;
import com.huatai.bpmn.service.TbCommitService;
import com.huatai.bpmn.utils.ServiceUtil;
import com.huatai.bpmn.utils.SqlUtil;
import com.huatai.common.api.R;
import groovy.lang.Binding;
import groovy.lang.GroovyShell;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;



/**
 * @author gusiyi
 * @version 1.0
 * @className TbTaskServiceImpl
 * @description 描述：
 * @date 2023/8/7 15:21
 */
@Service
@Slf4j
public class TbCommitServiceImpl extends ServiceImpl<TbCommitMapper, TbCommitEntity> implements TbCommitService {

	@Autowired
	private ServiceUtil serviceUtil;

	@Autowired
	private SqlUtil sqlUtil;

	@Override
	@Transactional(rollbackFor = RuntimeException.class)
	public Object commit(String deployKey, JSONObject data) {
		//必传的部署id与json格式数据
		TbCommitService tbCommitService = serviceUtil.tbCommitService;
		LambdaQueryWrapper<TbCommitEntity> commitQuery = Wrappers.lambdaQuery();
		commitQuery.eq(TbCommitEntity::getDeployKey,deployKey);
		TbCommitEntity theCommit = tbCommitService.getOne(commitQuery);
		if (theCommit == null){
			return R.data("无额外代码逻辑");
		}else {
			//groovy绑定变量
			Binding binding = new Binding();
			binding.setProperty("data", data);
			binding.setProperty("serviceUtil", serviceUtil);
			binding.setProperty("sqlUtil", sqlUtil);
			GroovyShell groovyShell = new GroovyShell(binding);
			Object result = null;
			try {
				result = groovyShell.evaluate(theCommit.getCommit());
			} catch (Exception e) {
				throw new RuntimeException(e.getMessage());
			}
			log.info(result.toString());
			return R.data(result);
		}
	}
}
